package com.party.admin.web.controller.mall;

import com.google.common.collect.Lists;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.biz.mall.MallShowGoodsBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.core.exception.BusinessException;
import com.party.core.model.mall.MallShowCategory;
import com.party.core.model.mall.MallShowGoods;
import com.party.core.model.mall.MallShowGoodsWithAuthor;
import com.party.core.model.mall.MallShowSubject;
import com.party.core.service.mall.IMallShowCategoryService;
import com.party.core.service.mall.IMallShowGoodsService;
import com.party.core.service.mall.IMallShowSubjectService;
import com.party.core.service.mall.biz.GoodsShowCountBizService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品导购
 *
 * @author cyl
 */
@Controller
@RequestMapping("/mall/showgoods")
public class MallShowGoodsController {

    protected static Logger logger = LoggerFactory.getLogger(MallShowGoodsController.class);


    @Autowired
    private IMallShowCategoryService mallShowCategoryService;

    @Autowired
    private IMallShowGoodsService mallShowGoodsService;

    @Autowired
    private MallShowGoodsBizService mallShowGoodsBizService;

    @Autowired
    private GoodsShowCountBizService goodsShowCountBizService;

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;

    @Autowired
    private DistributionBizService distributionBizService;


    @RequestMapping(value = "list")
    public ModelAndView showGoodsList(MallShowGoodsWithAuthor mallShowGoodsWithAuthor, Page page, String subjectId) {
        ModelAndView mv = new ModelAndView("mall/showGoodsList");
        mv.addObject("page", page);
        mv.addObject("subjectId", subjectId);
        mv.addObject("categoryId", mallShowGoodsWithAuthor.getCategoryId());
        List<MallShowGoodsWithAuthor> list = mallShowGoodsBizService.list(mallShowGoodsWithAuthor, page);
        mv.addObject("goodsList", list);
        return mv;
    }

    //编辑或发布新的导购商品
    @RequestMapping(value = "showgoodform")
    public ModelAndView showGoodForm(String id, String subjectId, String categoryId) {
        ModelAndView mv = new ModelAndView("mall/showGoodForm");
        mv.addObject("subjectId", subjectId);
        mv.addObject("categoryId", categoryId);
        //指定商品种类
        mv.addObject("category", mallShowCategoryService.get(categoryId));

        if (StringUtils.isNotEmpty(id)) {
            MallShowGoods showGood = mallShowGoodsService.get(id);
            mv.addObject("showGood", showGood);
        }

        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveShowGood(MallShowGoods mallShowGood) {
        try {
            mallShowGoodsBizService.saveBusiness(mallShowGood);
            return new AjaxResult(true);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("保存商品异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存商品异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "delete")
    public AjaxResult delShowGood(String id) {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(false);
        } else {

            // 统计商品数量
            try {
                goodsShowCountBizService.countGoodsNum(id, false);
            } catch (Exception e) {
                logger.error("删除商品时, 统计商品数量异常", e);
            }

            mallShowGoodsService.delete(id);
            return new AjaxResult(true);
        }
    }

    @ResponseBody
    @RequestMapping(value = "upDownUpdateSort")
    public AjaxResult upDownGoodsSort(String goodsId, String type, Page page, String categoryId) {
        if (StringUtils.isEmpty(type)) {
            return AjaxResult.error("操作类型不能为空");
        }
        if (StringUtils.isEmpty(goodsId)) {
            return AjaxResult.error("商品id不能为空");
        }
        MallShowGoodsWithAuthor mallShowGoodsWithAuthor_old = new MallShowGoodsWithAuthor();
        mallShowGoodsWithAuthor_old.setCategoryId(categoryId);
        List<MallShowGoodsWithAuthor> list = mallShowGoodsBizService.list(mallShowGoodsWithAuthor_old, null);
        int i = 1;
        List<MallShowGoods> mlist = new ArrayList<MallShowGoods>();
        for (MallShowGoodsWithAuthor msgwa : list) {
            String id = msgwa.getId();
            MallShowGoods mallShowGoods = mallShowGoodsService.get(id);
            mallShowGoods.setSort(i);
            mallShowGoodsService.update(mallShowGoods);
            mlist.add(mallShowGoods);
            i++;
        }
        String id = goodsId;
        MallShowGoods mallShowGoods = mallShowGoodsService.get(id);
        int msort = mallShowGoods.getSort();
        String afterid = "";
        String beforeid = "";
        for (MallShowGoods msg : mlist) {
            if ((msg.getId()).equals(id)) {
                int sort = msg.getSort();
                for (MallShowGoods msgid : mlist) {
                    if ((msgid.getSort()) == sort + 1) {
                        afterid = msgid.getId();
                    }
                    if (sort - 1 == (msgid.getSort())) {
                        beforeid = msgid.getId();
                    }
                }
            }
        }
        if ("up".equals(type)) {
            if (mallShowGoods.getSort() == 1) {
                return AjaxResult.error("已经是第一位了");
            }

            MallShowGoods beforemsg = mallShowGoodsService.get(beforeid);
            int beforesort = beforemsg.getSort();
            mallShowGoods.setSort(beforesort);
            beforemsg.setSort(msort);
            mallShowGoodsService.update(mallShowGoods);
            mallShowGoodsService.update(beforemsg);
        }
        if ("down".equals(type)) {
            if (mallShowGoods.getSort() == mlist.size()) {
                return AjaxResult.error("已经是最后一位了");
            }
            MallShowGoods aftermsg = mallShowGoodsService.get(afterid);
            int aftersort = aftermsg.getSort();
            mallShowGoods.setSort(aftersort);
            aftermsg.setSort(msort);
            mallShowGoodsService.update(mallShowGoods);
            mallShowGoodsService.update(aftermsg);
        }
        return new AjaxResult(true);
    }

    /**
     * 检查同一个类型下一个商品或者分类被绑定多次
     *
     * @param showCategoryId 展示商品类型id
     * @param targetId       目标id
     * @param type           类型
     * @param showGoodsId    展示商品id
     * @return
     */
    @ResponseBody
    @RequestMapping("checkTarget")
    public boolean checkTarget(String showCategoryId, String targetId, Integer type, String showGoodsId) {
        boolean flag = true;
        MallShowGoods showGoods = new MallShowGoods();
        showGoods.setCategoryId(showCategoryId);
        showGoods.setTargetId(targetId);
        showGoods.setType(type);
        List<MallShowGoods> mallShowGoods = mallShowGoodsService.list(showGoods);
        if (mallShowGoods.size() == 0) {
            flag = true;
        } else {
            for (MallShowGoods goods : mallShowGoods) {
                if (!goods.getId().equals(showGoodsId)) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * 初始化subjectId
     *
     * @return 执行成功次数
     */
    @ResponseBody
    @RequestMapping("initSubjectId")
    public AjaxResult initSubjectId() {
        Integer count = 0;
        List<MallShowGoods> mallShowGoods = mallShowGoodsService.list(new MallShowGoods());
        for (MallShowGoods showGoods : mallShowGoods) {
            String categoryId = showGoods.getCategoryId();
            if (StringUtils.isNotEmpty(categoryId)) {
                MallShowCategory mallShowCategory = mallShowCategoryService.get(categoryId);
                if (mallShowCategory != null) {
                    if (StringUtils.isNotEmpty(mallShowCategory.getSubjectId())) {
                        showGoods.setSubjectId(mallShowCategory.getSubjectId());
                    }
                    if (StringUtils.isNotEmpty(mallShowCategory.getTemplateId())) {
                        showGoods.setTemplateId(mallShowCategory.getTemplateId());
                    }
                    mallShowGoodsService.update(showGoods);
                    count++;
                }
            }
        }
        return AjaxResult.success(count);
    }

    /**
     * 初始化商品的分销关系
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("initDistributionRelation")
    public AjaxResult initDistributionRelation() {
        Integer count = 0;
        List<MallShowGoods> mallShowGoods = mallShowGoodsService.list(new MallShowGoods());
        for (MallShowGoods showGoods : mallShowGoods) {
            if (StringUtils.isNotEmpty(showGoods.getTargetId()) && StringUtils.isNotEmpty(showGoods.getSubjectId())) {
                MallShowSubject mallShowSubject = mallShowSubjectService.get(showGoods.getSubjectId());
                if (null != mallShowSubject) {
                    String orgId = mallShowSubject.getMemberId();
                    boolean result = distributionBizService.saveShowGoodsDistributionBiz(orgId, Lists.newArrayList(showGoods.getTargetId()));
                    if (result) {
                        count++;
                    }
                }
            }
        }
        return AjaxResult.success(count);
    }
}
